﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Se.Common
{
    /// <summary>
    /// XML序列化
    /// </summary>
    public static class XmlFormatter
    {
        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string Serialize<TEntity>(TEntity entity)
        {
            MemoryStream stream = new MemoryStream();
            try
            {
                var serializer = new XmlSerializer(typeof(TEntity));
                serializer.Serialize(stream, entity);
                return stream.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                stream.Close();
            }
        }
        /// <summary>
        /// 序列化
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static void Serialize<TEntity>(string fileName, TEntity entity)
        {
            FileStream stream = null;
            try
            {
                stream = File.OpenWrite(fileName);
                var serializer = new XmlSerializer(typeof(TEntity));
                serializer.Serialize(stream, entity);
                stream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static TEntity DeSerialize<TEntity>(string fileName)
        {
            TEntity entity = default(TEntity);
            FileStream stream = null;
            try
            {
                var serializer = new XmlSerializer(typeof(TEntity));
                stream = File.OpenRead(fileName);
                entity = (TEntity)serializer.Deserialize(stream);
                return entity;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
        }
    }
}
